package com.cloudpivot.receivales.esign.utils;

import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;

@Slf4j
public class HttpUtilNew {

    /**
     * 向指定URL发送GET方法的请求
     * @param url 发送请求的URL
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String appid, String token, boolean isGetToken) {
        String result = "";
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            if(!isGetToken){
                // 设置通用的请求属性
                connection.setRequestProperty("X-Tsign-Open-App-Id", appid);
                connection.setRequestProperty("X-Tsign-Open-Token", token);
                connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            }
            // 建立实际的连接
            connection.connect();

            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally { // 使用finally块来关闭输入流
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url      发送请求的 URL
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String requestBody, String appid, String token) {
        String result = "";
        BufferedReader in;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
            conn.setRequestMethod("POST");

            // 设置通用的请求属性
            conn.setRequestProperty("X-Tsign-Open-App-Id", appid);
            conn.setRequestProperty("X-Tsign-Open-Token", token);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setDoOutput(true);

            OutputStream os = conn.getOutputStream();
            os.write(requestBody.getBytes());
            os.flush();

            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }

            os.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 不带参数的post 请求
     *
     * @param url
     * @throws Exception
     */
    public static String sendPost(String url) {
        String result = "";
        BufferedReader in;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 发送PUT方法的请求
     *
     */
    public static String sendPut(String url, FileInputStream inputStream, String ContentMD5, String ContentType) {
        String result = "";
        BufferedReader in;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
            conn.setRequestMethod("PUT");

            // 设置请求属性
            log.info("ContentMD5："+ContentMD5);
            log.info("ContentType："+ContentType);
            conn.setRequestProperty("Content-MD5", ContentMD5);
            conn.setRequestProperty("Content-Type", ContentType);
            conn.setDoOutput(true);

            //OutputStream os = conn.getOutputStream();
            inputStream.getChannel().position(0);//因前面计算MD5时已经read()过，所以需要将文件指针重置到文件开头
            DataOutputStream os = new DataOutputStream(conn.getOutputStream());
            byte[] buffer = new byte[1024];
            int length = -1;
            while ((length = inputStream.read(buffer, 0, 1024)) != -1) {
                os.write(buffer, 0, length);
            }
            os.flush();
            os.close();

            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    // 下载文件并将其转为 Base64 字符串
    public static String downloadFileAsBase64(String fileURL) throws IOException {
        URL url = new URL(fileURL);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        int responseCode = httpConn.getResponseCode();

        // 检查HTTP响应码
        if (responseCode == HttpURLConnection.HTTP_OK) {

            // 将输入流内容保存为字节数组
            BufferedInputStream bis = new BufferedInputStream(httpConn.getInputStream());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024]; // 每次读取1024字节
            int bytesRead;

            // 逐步读取输入流内容
            while ((bytesRead = bis.read(buffer, 0, buffer.length)) != -1) {
                baos.write(buffer, 0, bytesRead);
            }

            // 将字节数组转换为Base64编码的字符串
            String base64String = Base64.getEncoder().encodeToString(baos.toByteArray());

            return base64String;
        }

        return null;
    }
}
